package lv.accenture.ex06;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sun.security.provider.MD5;

public class RegexExtractor implements IExtractor {

	public List<Bookmark> extractBookmarks(String resource) throws IOException {
		List<Bookmark> result = new ArrayList<Bookmark>();
		FileResourceReader reader = new FileResourceReader();
		List<String> lines = reader.readLines(resource);

		for (int i = 0; i < lines.size(); i++) {
			String line = lines.get(i);
			String title = new String();
			Pattern p0 = Pattern.compile("<item rdf:about=\"([^\"]+)\">");			
			Matcher m0 = p0.matcher(line);
			
			if (m0.matches()) { //found something
				Bookmark bm = new Bookmark();
				
				String url = m0.group(1);
				i++; //read title
				line = lines.get(i);
				Pattern p1 = Pattern.compile("<title>([^\"]+)</title>");
				Matcher m1 = p1.matcher(line);
				if (m1.matches())
				{
					title = m1.group(1);
				}
				

				i++;
				line = lines.get(i);
				
				Pattern p2 = Pattern.compile("<description>([^\"]*)</description>");
				Matcher m2 = p2.matcher(line);	
				while (!m2.matches())
				{
					i++;
					line = lines.get(i);
					m2 = p2.matcher(line);	
				}
			String description = m2.group(1);
				
			i++;
			line=lines.get(i);
			Pattern p3 = Pattern.compile("<dc:creator>([^\"]*)</dc:creator>");
			Matcher m3 = p3.matcher(line);
			String creator = new String(); 
			if (m3.matches())
			{
				creator = m3.group(1);
			}
			
			
			i++;
			line=lines.get(i);
			Pattern p4 = Pattern.compile("<dc:date>([^\"]+)</dc:date>");

			Matcher m4 = p4.matcher(line);
			String date = new String(); 
			
			if (m4.matches())
			{
				date = m4.group(1).substring(0, 4);
			}
			
			i++;
			line=lines.get(i);
			Pattern p5 = Pattern.compile("<dc:subject>([^\"]+)</dc:subject>");
			Matcher m5 = p5.matcher(line);
			String tags = new String();
			if (m5.matches())
			{
				tags = m5.group(1);
			}
			

			String[] tagArray = tags.split(" ");
			List<String> tagList = Arrays.asList(tagArray);
		
			
			
			bm.setTags(tagList);
			bm.setTitle(title);
			bm.setCreator(creator);
			bm.setDescription(description);
			bm.setUrl(url);
			bm.setYear(date);
			Integer hash=url.hashCode();
			bm.setUid(hash.toString()  );
			result.add(bm);
			
				
				
			}			
		}
		return result;
	}

}
